<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Models\Users;
use App\Services\MiniProgramService;
use App\Services\UserService;
use App\Services\WechatService;
use Illuminate\Http\Request;

/**
 * 微信控制器
 * Class WechatController
 * @package App\Http\Controllers\Api
 */
class WechatController extends Controller
{
    /**
     * 支付回调
     */
    public function notify()
    {
        WechatService::handleNotify();
    }

    /**
     * 新微信登录
     * @param Request $request
     * @return array
     */
    public function mpLogin(Request $request)
    {
        $code = $request->input('code', '');
        if(!$code){
            return $this->error(-1, '登录出错，请稍后重试');
        }
        $app = MiniProgramService::miniprogram();
        $session = $app->auth->session($code);
        if (!$session || $session['errcode']) {
            return $this->error(-1, $session['errmsg'], -1);
        }
        $wxapp_openid = $session['openid'];
        //判断是否有此用户信息
        $user = User::where('wxapp_openid', $wxapp_openid)->first();
        if(!$user){
            //加新的用户
            $userInfo['nickName'] = '微信用户';
            $userInfo['avatarUrl'] = 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132';
            $userInfo['wxapp_openid'] = $wxapp_openid;
            $userInfo['unionid'] = $session['unionid'];
            $data = (new UserService())->addUserInfo($userInfo);
        }else{
            $data = (new UserService())->addUserInfo(['wxapp_openid' => $wxapp_openid]);
        }
        return $this->success($data, '登录成功');
    }

}
